<template>
  <div id="team-report-container">
    <beetles-search :size="'mini'" @search-form="submitForm" @empty-form="emptyForm">
      <template slot-scope="{searchConceal}" slot="searchForm">
        <el-form :model="queryForm" ref="queryForm" label-width="100px" style="flex: 0">
          <div style="display: flex;flex-wrap: wrap">
            <el-form-item label="订单">
              <el-select size="mini" v-model="queryForm.offerId" clearable filterable style="width: 140px">
                <el-option v-for="item in offerList" :key="item.id" :value="item.id" :label="item.name">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="媒体">
              <el-select size="mini" v-model="queryForm.platform" clearable filterable style="width: 140px">
                <el-option v-for="(item,index) in platformsList"
                           :key="index"
                           :value="item.dictKey"
                           :label="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="日期">
              <el-date-picker
                size="mini"
                v-model="selectDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
          </div>
        </el-form>
      </template>
    </beetles-search>
    <basic-container>
      <div class="item-box">
        <div class="chart-title">优化师数据
        </div>
        <chart-op v-loading="loading1" type="op" id="opChart" :chart-data="opData" @click="showDetail"
                  ref="opChartRef"></chart-op>
        <div class="reload" v-show="reload1">
          <el-button type="info" @click="getOpData">重新加载</el-button>
        </div>
      </div>
      <div class="item-box">
        <div class="chart-title">设计师数据
        </div>
        <chart-op v-loading="loading2" type="design" id="designChart" :chart-data="designData" @click="showDetail"
                  ref="designChartRef"></chart-op>
        <div class="reload" v-show="reload2">
          <el-button type="info" @click="getDesignData">重新加载</el-button>
        </div>
      </div>
      <div class="item-box">
        <div class="chart-title">优化师设计师组合数据
          <el-tooltip content="统计数据只能匹配到系统上的已知素材，实际结果可能存在误差" placement="right">
            <el-image
              style="width: 13px; height: 13px"
              :src="images"
              fit="fit">
            </el-image>
          </el-tooltip>
        </div>
        <chart-op v-loading="loading3" type="op-design" id="opDesignChart" :chart-data="opDesignData"
                  @click="showDetail"
                  ref="opDesignChartRef"></chart-op>
        <div class="reload" v-show="reload3">
          <el-button type="info" @click="getOpDesignData">重新加载</el-button>
        </div>
      </div>
      <div class="item-box">
        <div class="chart-title">设计师优化师组合数据
          <el-tooltip content="统计数据只能匹配到系统上的已知素材，实际结果可能存在误差" placement="right">
            <el-image
              style="width: 13px; height: 13px"
              :src="images"
              fit="fit">
            </el-image>
          </el-tooltip>
        </div>
        <chart-op v-loading="loading4" type="design-op" id="designOpChart" :chart-data="designOpData"
                  @click="showDetail"
                  ref="designOpChartRef"></chart-op>
        <div class="reload" v-show="reload4">
          <el-button type="info" @click="getDesignOpData">重新加载</el-button>
        </div>
      </div>
    </basic-container>
    <!--详情弹窗-->
    <el-drawer
      title="详情"
      size="80%"
      :visible.sync="detailDialog"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      ref="drawer"
      @close="handleCloseDetail"
    >
      <el-divider></el-divider>
      <div class="drawer-box">
        <!--优化师数据详情-->
        <el-table
          v-loading="detailLoading"
          v-show="currentDetailType === 'op'"
          :data="opDetail"
          style="width: 100%"
          border
          :span-method="opTableSpanMethod"
          :header-cell-style="iHeaderCellStyle"
          height="250">
          <el-table-column
            prop="date"
            label="日期">
          </el-table-column>
          <el-table-column
            prop="offerName"
            label="订单">
          </el-table-column>
          <el-table-column
            prop="requestCount"
            label="需求数">
          </el-table-column>
          <el-table-column
            prop="platform"
            label="媒体">
          </el-table-column>
          <el-table-column
            prop="accountCount"
            label="有花费账户">
          </el-table-column>
          <el-table-column
            prop="spend"
            label="花费">
            <template v-slot="{ row }">
              {{ thousandSeparator(row.spend) }}
            </template>
          </el-table-column>
        </el-table>
        <!--设计师数据详情-->
        <el-table
          v-loading="detailLoading"
          v-show="currentDetailType === 'design'"
          :data="designDetail"
          style="width: 100%"
          border
          stripe
          :header-cell-style="iHeaderCellStyle"
          height="250">
          <el-table-column
            prop="date"
            label="日期">
          </el-table-column>
          <el-table-column
            prop="offerName"
            label="订单">
          </el-table-column>
          <el-table-column
            prop="videoCount"
            label="视频">
          </el-table-column>
          <el-table-column
            prop="imageCount"
            label="图片">
          </el-table-column>
          <el-table-column
            prop="requestCount"
            label="需求数">
          </el-table-column>
          <el-table-column
            prop="makeTime"
            label="制作用时">
            <template v-slot="{ row }">
              {{ (row.makeTime / 3600).toFixed(0) }}时{{ ((row.makeTime % 3600) / 60).toFixed(0) }}分
            </template>
          </el-table-column>
        </el-table>
        <!--优化师设计师组合数据详情-->
        <el-table
          v-loading="detailLoading"
          v-show="currentDetailType === 'op-design'"
          :data="opDesignDetail"
          style="width: 100%"
          border
          stripe
          :header-cell-style="iHeaderCellStyle"
          :span-method="opDesignTableSpanMethod"
          height="250">
          <el-table-column
            prop="date"
            label="日期">
          </el-table-column>
          <el-table-column
            prop="offerName"
            label="订单">
          </el-table-column>
          <el-table-column
            prop="designerName"
            label="设计师">
          </el-table-column>
          <el-table-column
            prop="videoCount"
            label="视频">
          </el-table-column>
          <el-table-column
            prop="imageCount"
            label="图片">
          </el-table-column>
          <el-table-column
            prop="requestCount"
            label="需求数">
          </el-table-column>
          <el-table-column
            prop="platform"
            label="媒体">
          </el-table-column>
          <el-table-column
            prop="spend"
            label="花费">
            <template v-slot="{ row }">
              {{ thousandSeparator(row.spend) }}
            </template>
          </el-table-column>
        </el-table>
        <!--设计师优化师组合数据详情-->
        <el-table
          v-loading="detailLoading"
          v-show="currentDetailType === 'design-op'"
          :data="designOpDetail"
          style="width: 100%"
          border
          stripe
          :span-method="designOpTableSpanMethod"
          :header-cell-style="iHeaderCellStyle"
          height="250">
          <el-table-column
            prop="date"
            label="日期">
          </el-table-column>
          <el-table-column
            prop="offerName"
            label="订单">
          </el-table-column>
          <el-table-column
            prop="opUserName"
            label="优化师">
          </el-table-column>
          <el-table-column
            prop="videoCount"
            label="视频">
          </el-table-column>
          <el-table-column
            prop="imageCount"
            label="图片">
          </el-table-column>
          <el-table-column
            prop="requestCount"
            label="需求数">
          </el-table-column>
          <el-table-column
            prop="platform"
            label="媒体">
          </el-table-column>
          <el-table-column
            prop="spend"
            label="花费">
            <template v-slot="{ row }">
              {{ thousandSeparator(row.spend) }}
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryDetailForm.current"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="queryDetailForm.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import beetlesSearch from "@/components/basic-components/beetles-search";
import ChartOp from "@/views/dataReport/team-report/components/ChartOp";
import {getSysDictList} from '@/api/system/dict'
import {getOfferList} from "@/api/business/offer";
import {
  queryDesignData, queryDesignDetailData,
  queryDesignOpData, queryDesignOpDetailData,
  queryOpData,
  queryOpDesignData, queryOpDesignDetailData,
  queryOpDetailData
} from "@/api/dataReport/team-report";
import {dateFormat} from "@/util/date";
import {thousandSeparator} from "@/util/util";

export default {
  name: "TeamReport",
  components: {
    beetlesSearch,
    ChartOp,
  },
  data() {
    return {
      loading1: false,
      loading2: false,
      loading3: false,
      loading4: false,
      // 重新加载
      reload1: false,
      reload2: false,
      reload3: false,
      reload4: false,
      // 优化师团队报表数据
      opData: [],
      // 设计师团队报表数据
      designData: [],
      // 优化师/设计师组合数据
      opDesignData: [],
      // 设计师/优化师组合数据
      designOpData: [],
      // 详情弹窗
      detailDialog: false,
      currentDetailType: '',
      // 优化师详情
      opDetail: [],
      // 设计师详情
      designDetail: [],
      // 优化师设计师组合详情
      opDesignDetail: [],
      // 设计师优化师组合详情
      designOpDetail: [],
      // 查询详情
      queryForm: {
        offerId: '',
        platform: '',
        startTime: '',
        endTime: '',
      },
      selectDate: [dateFormat(
        new Date(new Date(new Date().toLocaleDateString()).getTime() - 3600 * 1000 * 24 * 7), 'yyyy-MM-dd'), dateFormat(
        new Date(new Date(new Date().toLocaleDateString()).getTime() - 3600 * 1000 * 24), 'yyyy-MM-dd')],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 3600 * 1000 * 24;
        },
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              end.setTime(end.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近30天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              end.setTime(end.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近90天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              end.setTime(end.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一年',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
              end.setTime(end.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      platformsList: [],//媒体列表
      offerList: [],
      queryDetailForm: {
        offerId: '',
        startTime: '',
        endTime: '',
        platform: '',
        userId: '',
        current: 1,
        size: 10,
        reportType: 1
      },
      total: 0,
      detailLoading: false,
      images: '/img/icon/error.png',
    }
  },
  created() {
    // 获取订单列表
    this.getOfferList()
    // 查找媒体列表
    this.getPlatformsList()
    // 数据加载
    this.initData()

  },
  computed: {},
  watch: {
    'selectDate': {
      handler: function (val) {
        // 清空后默认为一周时间
        // const start = dateFormat(
        //   new Date(new Date(new Date().toLocaleDateString()).getTime() - 3600 * 1000 * 24 * 8), 'yyyy-MM-dd')
        // const end = dateFormat(
        //   new Date(new Date(new Date().toLocaleDateString()).getTime() - 3600 * 1000 * 24), 'yyyy-MM-dd')
        this.queryForm.startTime = val === null ? '' : val[0]
        this.queryForm.endTime = val === null ? '' : val[1]
        this.queryDetailForm.startTime = val === null ? '' : val[0]
        this.queryDetailForm.endTime = val === null ? '' : val[1]
      },
      immediate: true
    },
    'queryForm.offerId': function (val, oldVal) {
      this.queryDetailForm.offerId = val
      if (val !== oldVal) {
        this.detailDef = true
      }
    },
    'queryForm.platform': function (val) {
      this.queryDetailForm.platform = val
    },
    'queryDetailForm.userId': function (val, oldVal) {
      if (val !== oldVal) {
        this.detailDef = true
      }
    }
  },
  methods: {
    showDetail(data, type) {
      // console.log(data)
      // console.log(type)
      this.detailDialog = true
      this.currentDetailType = type
      this.queryDetailForm.userId = data.userId
      this.initDetail()
    },
    initDetail() {
      switch (this.currentDetailType) {
        case 'op':
          this.getOpDetailData()
          break
        case 'design':
          this.getDesignDetailData()
          break
        case 'op-design':
          this.getOpDesignDetailData()
          break
        case 'design-op':
          this.getDesignOpDetailData()
          break
      }
    },
    async handleSizeChange(val) {
      this.queryDetailForm.size = val
      // console.log(`每页 ${val} 条`);
      await this.initDetail()
    },
    async handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.queryDetailForm.current = val
      // console.log(`每页 ${val} 条`);
      await this.initDetail()
    },
    // 查询
    submitForm() {
      // if (!queryForm.startTime || !queryForm.endTime) {
      //   this.$message.error('必须选择日期');
      //   return;
      // }
      // if (Math.floor((this.selectDate[1].getTime() - this.selectDate[0].getTime())/(24*3600*1000)) > 30) {
      //   this.$message.error('日期最多只能选择30天');
      //   return;
      // }
      this.initData()
    },
    // 清空
    emptyForm() {
      this.selectDate = [dateFormat(
        new Date(new Date(new Date().toLocaleDateString()).getTime() - 3600 * 1000 * 24 * 8), 'yyyy-MM-dd'), dateFormat(
        new Date(new Date(new Date().toLocaleDateString()).getTime() - 3600 * 1000 * 24), 'yyyy-MM-dd')]
      this.queryForm.offerId = ''
      this.queryForm.platform = ''
      this.$refs.queryForm.resetFields();
      this.submitForm();
    },
    // 获取媒体列表
    async getPlatformsList() {
      const {platforms} = await getSysDictList('platforms')
      this.platformsList = platforms
    },
    // 获取订单列表
    async getOfferList() {
      const {data: res} = await getOfferList()
      if (res.code !== 200) return this.$message.error('获取订单列表失败')
      this.offerList = res.data
    },
    // 获取优化师数据
    async getOpData() {
      this.loading1 = true
      this.reload1 = false
      const {data: res} = await queryOpData(this.queryForm).catch(err => {
        this.$message.error('获取优化师数据加载失败，请重新加载')
        this.reload1 = true
      })
      this.loading1 = false
      if (res.code !== 200) return this.$message.error('获取优化师数据失败')
      this.opData = res.data
      this.$nextTick(() => {
        this.$refs.opChartRef.initChart()
      })
    },
    // 获取设计师数据
    async getDesignData() {
      this.loading2 = true
      this.reload2 = false
      const {data: res} = await queryDesignData(this.queryForm).catch(err => {
        this.$message.error('获取优化师数据加载失败，请重新加载')
        this.reload2 = true
      })
      this.loading2 = false
      if (res.code !== 200) return this.$message.error('获取设计师数据失败')
      this.designData = res.data
      this.$nextTick(() => {
        this.$refs.designChartRef.initChart()
      })
    },
    // 获取优化师设计师组合数据
    async getOpDesignData() {
      this.loading3 = true
      this.reload3 = false
      const {data: res} = await queryOpDesignData(this.queryForm).catch(err => {
        this.$message.error('获取优化师数据加载失败，请重新加载')
        this.reload3 = true
      })
      this.loading3 = false
      if (res.code !== 200) return this.$message.error('获取优化师设计师组合数据失败')
      this.opDesignData = res.data
      this.$nextTick(() => {
        this.$refs.opDesignChartRef.initChart()
      })
    },
    // 获取设计师优化师组合数据
    async getDesignOpData() {
      this.loading4 = true
      this.reload4 = false
      const {data: res} = await queryDesignOpData(this.queryForm).catch(err => {
        this.$message.error('获取优化师数据加载失败，请重新加载')
        this.reload4 = true
      })
      this.loading4 = false
      if (res.code !== 200) return this.$message.error('获取设计师优化师组合数据失败')
      this.designOpData = res.data
      this.$nextTick(() => {
        this.$refs.designOpChartRef.initChart()
      })
    },
    // 获取优化师详情数据
    async getOpDetailData() {
      this.detailLoading = true
      const {data: res} = await queryOpDetailData(this.queryDetailForm).catch(err => err)
      this.detailLoading = false
      if (res.code !== 200) return this.$message.error('获取优化师数据失败')
      this.opDetail = res.data.records
      this.total = res.data.total
    },
    // 获取设计师详情数据
    async getDesignDetailData() {
      this.detailLoading = true
      const {data: res} = await queryDesignDetailData(this.queryDetailForm).catch(err => err)
      this.detailLoading = false
      if (res.code !== 200) return this.$message.error('获取优化师数据失败')
      this.designDetail = res.data.records
      this.total = res.data.total
    },
    // 获取优化师设计师组合详情数据
    async getOpDesignDetailData() {
      this.detailLoading = true
      const {data: res} = await queryOpDesignDetailData(this.queryDetailForm).catch(err => err)
      this.detailLoading = false
      if (res.code !== 200) return this.$message.error('获取优化师数据失败')
      this.opDesignDetail = res.data.records
      this.total = res.data.total
    },
    // 获取师优化师组合详情数据
    async getDesignOpDetailData() {
      this.detailLoading = true
      const {data: res} = await queryDesignOpDetailData(this.queryDetailForm).catch(err => err)
      this.detailLoading = false
      if (res.code !== 200) return this.$message.error('获取优化师数据失败')
      this.designOpDetail = res.data.records
      this.total = res.data.total
    },
    async initData() {
      await Promise.all([
        this.getOpData(),
        this.getDesignData(),
        this.getOpDesignData(),
        this.getDesignOpData(),
      ]);
    },
    // 关闭详情
    handleCloseDetail() {
      this.opDetail = []
      this.designDetail = []
      this.opDesignDetail = []
      this.designOpDetail = []
      this.queryDetailForm.current = 1
      this.queryDetailForm.size = 10
    },
    // 千分位
    thousandSeparator(num) {
      return thousandSeparator(num)
    },
    //
    opTableSpanMethod({row, column, rowIndex, columnIndex}) {
      // console.log('row', row)
      // console.log('column', column);
      // console.log('rowIndex', rowIndex);
      // console.log('columnIndex', columnIndex);
      const same = this.opDetail.filter(item => item.date === row.date && item.offerId === row.offerId && item.requestCount === row.requestCount)
      if (same.length >= 2) {
        same.forEach((item, index) => {
          if (!item.hasOwnProperty('row')) {
            if (index === 0) {
              item.row = same.length
            } else {
              item.row = 0
            }
          }
        })
      }
      if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2) {
        if (row.hasOwnProperty('row')) {
          return {
            rowspan: row.row,
            colspan: 1
          }
        }
      }
    },
    iHeaderCellStyle() {
      return {
        color: '#101010',
        backgroundColor: '#F2F2F2'
      }
    },
    opDesignTableSpanMethod({row, column, rowIndex, columnIndex}) {
      const same = this.opDesignDetail.filter(item => item.date === row.date
        && item.offerId === row.offerId
        && item.designerId === row.designerId
        && item.videoCount === row.videoCount
        && item.imageCount === row.imageCount
        && item.requestCount === row.requestCount)
      if (same.length >= 2) {
        same.forEach((item, index) => {
          if (!item.hasOwnProperty('row')) {
            if (index === 0) {
              item.row = same.length
            } else {
              item.row = 0
            }
          }
        })
      }
      if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4 || columnIndex === 5) {
        if (row.hasOwnProperty('row')) {
          return {
            rowspan: row.row,
            colspan: 1
          }
        }
      }
    },
    designOpTableSpanMethod({row, column, rowIndex, columnIndex}) {
      const same = this.designOpDetail.filter(item => item.date === row.date && item.offerId === row.offerId
        && item.requestCount === row.requestCount
        && item.videoCount === row.videoCount
        && item.imageCount === row.imageCount
        && item.opUserId === row.opUserId)
      if (same.length >= 2) {
        same.forEach((item, index) => {
          if (!item.hasOwnProperty('row')) {
            if (index === 0) {
              item.row = same.length
            } else {
              item.row = 0
            }
          }
        })
      }
      if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4 || columnIndex === 5) {
        if (row.hasOwnProperty('row')) {
          return {
            rowspan: row.row,
            colspan: 1
          }
        }
      }
    },
  }
}
</script>

<style lang="scss" scoped>
#team-report-container {
  .item-box {
    position: relative;
    margin-bottom: 100px;

    .chart-title {
      font-size: 18px;
      font-family: SimHei;
      font-weight: bold;
      color: #101010;
      box-sizing: border-box;

      &:before {
        content: '';
        display: inline-block;
        width: 13px;
        height: 32px;
        background-color: #FF944B;
        border-radius: 25%;
        vertical-align: -40%;
        margin-right: 20px;
      }
    }

    .reload {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 99999;
    }
  }
}

.drawer-box {
  padding: 0 25px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  height: 90%;
}

</style>
